<template>
  <div class="repository-container">
    <div class="repository-header">
      <h3>知识库文档管理</h3>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入文档名称搜索"
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
        <el-upload
          class="upload-btn"
          :http-request="handleFileUpload"
          :show-file-list="false"
          accept=".txt,.doc,.docx,.pdf,.json"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
        >
          <el-button type="primary" icon="el-icon-upload" class="large-upload-btn">
            上传文件
          </el-button>
        </el-upload>
      </div>
    </div>
    
    <div class="document-list">
      <el-card v-if="documents.length === 0" class="empty-state">
        <div class="empty-content">
          <i class="el-icon-document empty-icon"></i>
          <p>暂无文档，点击上方按钮上传</p>
        </div>
      </el-card>
      
      <el-table v-else :data="documents"  border size="small">
        <el-table-column prop="title" label="文档名称" width="400">
          <template #default="scope">
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="formattedDate" label="上传日期" >
          <template #default="scope">
            <span>{{ scope.row.formattedDate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wordCount" label="字数" >
          <template #default="scope">
            <span>{{ scope.row.wordCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="isInWorkspace(scope.row.name)"
              type="danger" 
              icon="el-icon-download" 
              class="large-upload-btns"  
              @click="removeFromBuffer(scope.row.name)">
              移出工作区
            </el-button>
            <el-button 
              v-else
              type="primary" 
              icon="el-icon-upload" 
              class="large-upload-btns"  
              @click="moveToBuffer(scope.row.id)">
              移入工作区
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :current-page.sync="pageNum"
          :page-size.sync="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui';
import request from '@/utils/request';

export default {
  name: 'RepositoryManage',
  data() {
    return {
      // 文档列表数据
      documents: [],
      // 总条数
      total: 0,
      // 当前页码
      pageNum: 1,
      // 每页显示条数
      pageSize: 10,
      // 所有文档数据（用于前端分页）
      allDocuments: [],
      // 工作区文件列表
      workspaceFiles: [],
      // 搜索关键字
      searchKeyword: ''
    };
  },
  mounted() {
    // 组件挂载时获取文档列表
    this.fetchDocuments();
  },
  methods: {
    // 获取文档列表
    async fetchDocuments() {
      try {
        // 同时请求两个接口
        const [listResponse, workspaceResponse] = await Promise.all([
          request({
            url: '/document/list',
            method: 'get'
          }),
          request({
            url: '/document/workspace/list',
            method: 'get'
          })
        ]);
        
        // 处理文档列表数据
        if (listResponse.code === 0 && listResponse.data) {
          // 处理响应数据
          let allDocuments = [];
          
          // 遍历根目录下的所有文件夹和文件
          listResponse.data.forEach(item => {
            if (item.type === 'folder' && item.items && item.items.length > 0) {
              // 提取文件夹中的文件并格式化日期，同时保留文件夹名称
              const folderDocuments = item.items.map(doc => ({
                ...doc,
                folderName: item.name, // 保留文件夹名称
                formattedDate: this.formatDate(doc.published)
              }));
              allDocuments = [...allDocuments, ...folderDocuments];
            }
          });
          
          // 存储所有文档数据
          this.allDocuments = allDocuments;
          // 执行搜索过滤
          this.handleSearch();
        } else {
          Message.error('获取文档列表失败');
        }
        
        // 处理工作区文件数据
        if (workspaceResponse.code === 0 && workspaceResponse.data) {
          // 存储工作区文件列表
          this.workspaceFiles = workspaceResponse.data;
        }
      } catch (error) {
        console.error('获取数据出错:', error);
        Message.error('获取数据失败，请重试');
      }
    },
    
    // 搜索功能
    handleSearch() {
      // 重置页码
      this.pageNum = 1;
      // 执行前端分页
      this.setPageData();
    },
    
    // 设置分页数据
    setPageData() {
      // 根据搜索关键字过滤文档
      let filteredDocuments = this.allDocuments;
      
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase();
        filteredDocuments = this.allDocuments.filter(doc => 
          doc.title.toLowerCase().includes(keyword) || 
          doc.name.toLowerCase().includes(keyword)
        );
      }
      
      // 更新总条数
      this.total = filteredDocuments.length;
      // 执行分页
      const start = (this.pageNum - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.documents = filteredDocuments.slice(start, end);
    },
    
    // 分页大小改变时的处理函数
    handleSizeChange(size) {
      this.pageSize = size;
      this.pageNum = 1; // 重置为第一页
      this.setPageData();
    },
    
    // 当前页码改变时的处理函数
    handleCurrentChange(current) {
      this.pageNum = current;
      this.setPageData();
    },

    // 格式化日期，只显示日期部分
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}/${month}/${day}`;
    },

    // 处理文件上传
    async handleFileUpload(options) {
      const { file } = options;
      const formData = new FormData();
      formData.append('file', file);
      
      try {
        const response = await request({
          url: '/document/upload',
          method: 'post',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          timeout: 60000 // 增加超时时间
        });
        
        if (response.code === 0) {
          options.onSuccess(response);
        } else {
          options.onError(new Error(response.msg || '上传失败'));
        }
      } catch (error) {
        options.onError(error);
      }
    },

    // 上传成功回调
    handleUploadSuccess() {
      Message.success('文件上传成功');
      // 重新获取文档列表
      this.fetchDocuments();
    },

    // 上传失败回调
    handleUploadError(error) {
      Message.error(`文件上传失败：${error.message || '未知错误'}`);
    },

    // 移入工作区
    moveToBuffer(documentId) {
      MessageBox.confirm('确定要将该文档移入工作区吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 从所有文档中找到对应的文档对象
          const document = this.allDocuments.find(doc => doc.id === documentId);
          
          if (document && document.folderName) {
            // 拼接文件夹名称和文档名称
            const param = `${document.folderName}/${document.name}`;
            
            // 调用后端接口，传递拼接后的参数
            const response = await request({
              url: '/document/add/workspace/llm',
              method: 'get',
              params: {
                name: param
              }
            });
            
            if (response.code === 0) {
              Message.success('文档已移入工作区');
              this.fetchDocuments();
            } else {
              Message.error(response.msg || '移入工作区失败');
            }
          } else {
            // 如果没有找到文档或文件夹信息
            // 这里使用文档名称作为替代方案
            const response = await request({
              url: '/add/workspace/llm',
              method: 'get',
              params: {
                name: document ? document.name : ''
              }
            });
            
            if (response.code === 0) {
              Message.success('文档已移入工作区');
              this.fetchDocuments();
            } else {
              Message.error(response.msg || '移入工作区失败');
            }
          }
        } catch (error) {
          console.error('移入工作区出错:', error);
          Message.error('移入工作区失败');
        }
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    // 移出工作区
    removeFromBuffer(filename) {
      MessageBox.confirm('确定要将该文档移出工作区吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 从工作区文件列表中查找对应的docpath
          const workspaceFile = this.workspaceFiles.find(file => file.filename === filename);
          
          if (workspaceFile && workspaceFile.docpath) {
            // 调用后端接口，传递docpath参数
            const response = await request({
              url: '/document/remove/workspace/llm',
              method: 'delete',
              params: {
                docpath: workspaceFile.docpath
              }
            });
            
            if (response.code === 0) {
              Message.success('文档已移出工作区');
              // 重新获取数据以更新界面
              this.fetchDocuments();
            } else {
              Message.error(response.msg || '移出工作区失败');
            }
          } else {
            Message.error('未找到对应的文档路径');
          }
        } catch (error) {
          console.error('移出工作区出错:', error);
          Message.error('移出工作区失败');
        }
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    // 判断文件是否在工作区中
    isInWorkspace(filename) {
      // 检查文件名是否存在于工作区文件列表中
      return this.workspaceFiles.some(file => file.filename === filename);
    }
  }
};
</script>

<style scoped lang="scss">
.repository-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.repository-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.repository-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 300px;
}

.document-list {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.upload-btn {
  display: inline-block;
}

.large-upload-btn {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
  padding: 12px 24px;
  font-size: 14px;
}

.large-upload-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  color: white;
}

.large-upload-btns {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
  padding: 6px 12px;
  font-size: 12px;
  height: 35px;
}

.large-upload-btns:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  color: white;
}

.el-table {
  width: 100%;
}

.el-table__header-wrapper th {
  background-color: #fafafa !important;
  font-weight: 500;
}

.el-table__body-wrapper {
  overflow-x: auto;
}

.el-button--small {
  padding: 5px 12px;
  font-size: 12px;
}
</style>
